package com.simple.upms.biz.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simple.upms.api.dto.UserInfo;
import com.simple.upms.api.entity.SysRole;
import com.simple.upms.api.entity.SysUser;
import com.simple.upms.api.vo.MenuVO;
import com.simple.upms.biz.mapper.SysUserMapper;
import com.simple.upms.biz.service.SysMenuService;
import com.simple.upms.biz.service.SysRoleService;
import com.simple.upms.biz.service.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统用户服务impl
 *
 * @author Administrator
 * @date 2021/01/04 13:52:55
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysRoleService roleService;
    @Resource
    private SysMenuService menuService;


    /**
     * 查询用户的全部信息，包括基本信息、权限和角色
     *
     * @param sysUser 系统用户
     * @return {@link UserInfo}
     */
    @Override
    public UserInfo getUserInfo(SysUser sysUser) {
        UserInfo userInfo = new UserInfo();
        // 设置用户基本信息
        userInfo.setSysUser(sysUser);

        // 设置角色ID列表
        List<String> roleIds = roleService.findRolesByUserId(sysUser.getUserId()).parallelStream().map(SysRole::getRoleId)
                .collect(Collectors.toList());
        userInfo.setRoles(ArrayUtil.toArray(roleIds, String.class));

        //设置权限列表(menu.permission)
        Set<String> permissions = new HashSet<>(16);
        roleIds.forEach(roleId -> {
            List<String> menuPermList = menuService.findMenuByRoleId(roleId).stream()
                    .map(MenuVO::getPerms)
                    .filter(StrUtil::isNotEmpty)
                    .collect(Collectors.toList());
            permissions.addAll(menuPermList);
        });
        userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class));

        return userInfo;
    }
}
